define(["jquery","bbcare","comm/form/form","comm/dtext/dtext",
	"bch/app/patientManager/user.servers","bch/app/patientManager/user.ui"],
	function($,$bb,$form,$dtext,$servers,$ui){
	var event = {}, defaults = {};

	/**
	 * 提交任务成功后的回调函数
	 */
	var ajaxSubmitTaskCallBack = function(data,params){
		$("."+params.className).modal("hide");
		var nodeIndex = Number( $("#userCp .item.active").attr("index") );
		event.init(nodeIndex);
	}

	/**
	 * 点击保存  提交任务
	 */
	var onSubmitTask = function(){
		if( $form.validate("questBox") ){
			var data = $(this).data("data");
			var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
			var channelId = $bb.getChannelId();
			var contList = $form.getSaveData("questBox");
			var userName = $("#userInfo .babycardCheck-name").text();
			var params1 = {
				"oprInfo":{
					"opCode":"1001",
					"opType":"2",
					"opNote":"【"+doctorName+"】医生对【"+userName+"】患者进行任务提交",
					"channelType":"2",
					"channelId":channelId,
				},
				"taskInfo":{
					"ptTaskId":data.params.curTask.id,
					"contList":contList
				},
				"saveType":data.saveType,
			};
			$servers.ajaxSubmitTask(params1,ajaxSubmitTaskCallBack,data.params);
		}
	}

	/**
	 * 评估公共方法
	 */
	var assess = function(params,url){
		$.get(url,function(html){
			var h = '<div class="assess-wrap">' + html + '</div>';
			$("#editBox").html(h);
			$("#editBox .assess-wrap").data("ptTaskId",params.curTask.id);
			$("." + params.className).modal('show');
			// 作用：评估后重新渲染（为了“已完成”的标志）
			$("." + params.className).on('hidden.bs.modal', function () {
			  	var nodeIndex = Number( $("#userCp .item.active").attr("index") );
				event.init(nodeIndex);
			});
		});
	}

	/**
	 * 问卷模态框
	 */
	var modalCont = function(data,params){
		if( params.curTask.templType == "01" ){
			var getParams = $bb.getPageParams();
			// 如果是疫苗的话，疫苗默认值
			if( getParams.busiTypeList && $.isArray(getParams.busiTypeList) && $.inArray("A0401",getParams.busiTypeList) > -1 ){
				data.valueList = $servers.getValueVaccine(params,data.valueList);
			}
			// 下次随访时间默认值
			data.valueList = $servers.getValueNextFollowDate(data.valueList,params.curNode.nextFollowDate);
			$ui.questWrap({
				"dom":$("#editBox"),
				"synchFlag":data.synchFlag,
				"curTask":params.curTask // 为了体格评估，快捷打印跳转按钮
			});
			var calcTestTime = params.curNode.diagnosisDate ? params.curNode.diagnosisDate : params.curNode.executeDate ? params.curNode.executeDate : $bb.simple.getCurTime().date;
			var preNodeId = $("#userCp .item.active").attr("data-preId");
		    $form.init({
				"id":"questBox",
				"questions":data.contList,
				"values":data.valueList,
				"event":{
					"userId":defaults.userId,
					"gender":defaults.gender,
					"calcTestTime":calcTestTime,
					"preNodeId":preNodeId
				}
			});
		    $("."+ params.className).modal('show');
		    // 暂存
		    $("#questSave").unbind("click");
		    $("#questSave").data("data",{"params":params,"saveType":"1"});
		    $("#questSave").click(onSubmitTask);
		    // 保存并发送
		    if( $("#questSaveAndSend").length > 0 ){
		    	$("#questSaveAndSend").unbind("click");
			    $("#questSaveAndSend").data("data",{"params":params,"saveType":"2"});
			    $("#questSaveAndSend").click(onSubmitTask);
		    }
		    // 体格评估快捷打印跳转按钮
		    if( $("#gotoReport").length > 0 ){
		    	$("#gotoReport").click(function(){
		    		$bb.openPage("growthDetail",{"userId":defaults.userId});
		    	});
		    }
		}else if( params.curTask.templType == "02" ){ //评估量表 
			if( data.contList && data.contList.length > 0 && data.contList[0].templData ){
				if( data.valueList && data.valueList.length > 0 ){
					// 为了将参数传过去。
					$('#content-main').data("params",data.valueList[0]);
					assess(params,data.contList[0].templData.urlReport);
				}else{
					assess(params,data.contList[0].templData.urlAssess);
				}
			}
		}
	}

	/**
	 * 查询某个任务实例下的内容
	 */
	var ajaxContCallBack = function(data,params){
		modalCont(data,params);
	}

	/**
	 * 点击箭头 查看上一个/下一个任务
	 */
	var editWrapInit = function(tasks,index,params){
		var preTaskBtnShow = index > 0 ? true : false;
		var nextTaskBtnShow = index < tasks.length-1 ? true : false;
		$ui.editWrap({
			"dom":$("." + params.className + " .modal-body"),
			"preTaskBtnShow":preTaskBtnShow,
			"nextTaskBtnShow":nextTaskBtnShow,
		});
		params.curTask = tasks[index];
		$("." + params.className + " .modal-header .modal-title").html(params.curTask.taskName);
		$servers.ajaxCont(params,ajaxContCallBack);
		// 上一个任务
		$("." + params.className + " .modal-body .editModal-wrap .user-arrow-left").unbind("click");
		$("." + params.className + " .modal-body .editModal-wrap .user-arrow-left").click(function(){
			index--;
			editWrapInit(tasks,index,params);
		});
		// 下一个任务
		$("." + params.className + " .modal-body .editModal-wrap .user-arrow-right").unbind("click");
		$("." + params.className + " .modal-body .editModal-wrap .user-arrow-right").click(function(){
			index++;
			editWrapInit(tasks,index,params);
		});
	}

	/**
	 * 点击某一任务的编辑按钮
	 */
	var onTaskSelect = function(){
		var data = $(this).data("data");
		var curNode = data.node, tasks = data.tasks;
		var index = $(this).parents(".item").index();
		var params = {
			"className":"questModal",
			"curNode":curNode,
			"curTask":tasks[index]
		};
		$bb.modal({
			"id":"user-modal",
			"className": params.className,
			"size":"modal-lg",
            "tit": params.curTask.taskName,
		},function(){
			// 初始化
			editWrapInit(tasks,index,params);
        });
	}

	/**
	 * 查询节点下的任务成功后的回调函数
	 */
	var ajaxTasksCallBack = function(data,curNode){
		$ui.tasks({
			"id":"userTasks",
			"list":data.rows,
			"node":curNode,
		});
		$(function(){ $('[data-toggle="tooltip"]').tooltip() });
		$("#userTasks .icon-click").unbind("click");
		$("#userTasks .icon-click").data("data",{"node":curNode,"tasks":data.rows});
		$("#userTasks .icon-click").click(onTaskSelect);
	}

	/**
	 * 取消修改时间
	 */
	var onCancelEditDate = function(){
		var className = $(this).data("className");
		$("." + className).modal("hide");
	}

	/**
	 * 修改节点实例计划日期成功后的回调函数
	 */
	var ajaxModifyDateCallBack = function(data,curNode){
		$("." + curNode.className).modal("hide");
		event.init(curNode.index);
	}

	/**
	 * 计划日期修改提交
	 */
	var onSubmitEditExecuteDate = function(){
		var channelId = $bb.getChannelId();
		var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
		var userName = $("#userInfo .babycardCheck-name").text();
		var curNode = $(this).data("curNode");
		var executeDate = $("." + curNode.className + " input[name=executeDate]").val();
		var winDay = Number( $("." + curNode.className + " input[name=winDay]").val() );
		var flag = $("." + curNode.className + " select[name=flag]").val();
		var params = {
			"oprInfo":{
				"opCode":"1217",
				"opType":"2",
				"opNote":"【"+ doctorName +"】医生给【"+ userName +"】患者修改了【"+ curNode.nodeName +"】节点的计划日期",
				"channelType":"2",
				"channelId":channelId,
			},
			"nodeInfo":{
				"ptNodeId":curNode.id,
				"executeDate":executeDate,
				"winDay":winDay,
				"flag":flag,
			}
		};
		$servers.ajaxModifyPtNodeWinDate(params,ajaxModifyDateCallBack,curNode);
	}

	/**
	 * 诊疗日期修改提交
	 */
	var onSubmitEditDiagnosisDate = function(){
		var channelId = $bb.getChannelId();
		var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
		var userName = $("#userInfo .babycardCheck-name").text();
		var curNode = $(this).data("curNode");
		var diagnosisDate = $("." + curNode.className + " input[name=diagnosisDate]").val();
		var params = {
			"oprInfo":{
				"opCode":"1216",
				"opType":"2",
				"opNote":"【"+ doctorName +"】医生给【"+ userName +"】患者修改了【"+ curNode.nodeName +"】节点的诊疗日期",
				"channelType":"2",
				"channelId":channelId,
			},
			"nodeInfo":{
				"ptNodeId":curNode.id,
				"diagnosisDate":diagnosisDate,
			}
		};
		$servers.ajaxModifyPtNodeAuthDiagDate(params,ajaxModifyDateCallBack,curNode);
	}

	/**
	 * 修改日期（计划日期、诊疗日期）还未完成
	 */
	var onEditDate = function(){
		var curNode = $(this).data("curNode");
		var name = $(this).parent().prev().find("span").html();
		var flag = name == "计划日期" ? "1" : "2"; // flag为1代表计划日期，为2代表诊疗日期
		var className = "editDateModal";
		$bb.modal({
			"className": className,
            "tit": "修改" + name,
		},function(){
			$ui.editDateWrap({
				"dom":$("." + className + " .modal-body")
			});
			$ui.editDate({
				"id":"editDateBox",
				"data":curNode,
				"flag":flag
			});
			$("." + className).modal("show");
			$("." + className + " .editDate-cancel").unbind("click");
			$("." + className + " .editDate-cancel").data("className",className);
			$("." + className + " .editDate-cancel").click(onCancelEditDate);
			$.extend(curNode,{"className":className});
			$("." + className + " .editDate-submit").unbind("click");
			$("." + className + " .editDate-submit").data("curNode",curNode);
			if( flag == "1" ){
				$("." + className + " .editDate-submit").click(onSubmitEditExecuteDate);
			}else if ( flag == "2" ){
				$("." + className + " .editDate-submit").click(onSubmitEditDiagnosisDate);
			}
		});
	}

	/**
	 * 添加临时随访节点成功后的回调函数
	 */
	var ajaxAddTempPtCpNodeCallBack = function(data){
		event.init(null,data.id);
	}

	/**
	 * 添加临时随访节点
	 */
	var addTempPtCpNode = function(curNode){
		var params = $bb.getPageParams();
		var channelId = $bb.getChannelId();
		var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
		var userName = $("#userInfo .babycardCheck-name").text();
		var params1 = {
			"oprInfo":{
				"opCode":"1018",
				"opType":"2",
				"opNote":"【"+ doctorName +"】医生给【"+ userName +"】患者添加临时随访节点",
				"channelType":"2",
				"channelId":channelId,
			},
			"nodeInfo":{
				"ptNodeId":curNode.id,
				"busiTypeList":params.busiTypeList,
				"subBusiTypeList":params.subBusiTypeList,
			}
		};
		$servers.ajaxAddTempPtCpNode(params1,ajaxAddTempPtCpNodeCallBack);
	}

	/**
	 * 添加临时节点
	 */
	var onAddTempNode = function(){
		var curNode = $(this).data("curNode");
		$bb.toastConfirmShow(addTempPtCpNode,curNode,"确定添加临时记录？");
	}

	/**
	 * 是否存在临时随访节点模板
	 */
	var ajaxChkNewTempCpNodeCallBack = function(data,params){
		if( data.isNew ){
			$("#userAddTempNode").css({"display":"block"});
			// 添加临时节点
			$("#userAddTempNode").unbind("click");
			$("#userAddTempNode").data("curNode",params);
			$("#userAddTempNode").click(onAddTempNode);
		}else{
			$("#userAddTempNode").css({"display":"none"});
		}
	}

	/**
	 * 选择节点
	 */
	var onCpSelect = function(){
		var isclick = $(this).attr("data-isclick");
		if( isclick == "Y" ){
			$(this).addClass("active").siblings().removeClass("active");
			var data = $(this).data("data");
			var index = $(this).index();
			var M = 5;
			if( index == 0 && data.list[index].index > 0 ){
				nodesInit(data.nodes,data.list[index].index);
			}else if( index == M - 1 && data.list[index].index < data.nodes.length -1 ){
				nodesInit(data.nodes,data.list[index].index);
			}
			// 获取当前节点的数据
			var curData = data.list[index];
			// 当前样式
			var h = ".user-cp .item.active:before { border-top-color: "+ curData.color +"; }" +
					".user-cp .item.active { border-color: "+ curData.color +"; }";
			$("#style").html(h);
			// 初始化各种日期
			$ui.dates({
				"id":"userDates",
				"data":curData
			});
			// 添加临时节点按钮是否显示(因为busiTypeList、subBusiTypeList两者必须传一个，否则接口报错)
			var params1 = $bb.getPageParams();
			if( params1.busiTypeList || params1.subBusiTypeList ) $servers.ajaxChkNewTempCpNode(curData,ajaxChkNewTempCpNodeCallBack);
			// 修改计划日期
			$("#userDates .executeDate-edit").unbind("click");
			$("#userDates .executeDate-edit").data("curNode",curData);
			$("#userDates .executeDate-edit").click(onEditDate);
			// 修改诊疗日期
			$("#userDates .diagnosisDate-edit").unbind("click");
			$("#userDates .diagnosisDate-edit").data("curNode",curData);
			$("#userDates .diagnosisDate-edit").click(onEditDate);
			// 初始化任务
			$servers.ajaxTasks(curData,ajaxTasksCallBack);
		}else{
			//$bb.toastShow("还未到随访时间，您可以通过右上角添加临时记录！");
			$bb.toastShow("还未到随访时间！");
		}
	}

	/**
	 * 节点初始化
	 */
	var nodesInit = function(nodes,index,params){
		if( params ) $.extend(defaults,params);
		var list = $servers.handleUserCpNodes(nodes,index);
		$ui.nodes({
			"id":"userCp",
			"list":list
		});
		$(function(){ $('[data-toggle="tooltip"]').tooltip() });
		// 点击节点
		$("#userCp .item").unbind("click");
		$("#userCp .item").data("data",{"nodes":nodes,"list":list});
		$("#userCp .item").click(onCpSelect);
		var eq = $servers.getCurrentIndex(list,index);
		$("#userCp .item").eq(eq).click();
	}

	/**
	 * 查询临床路径下的节点
	 */
	var ajaxUserCpNodesCallBack = function(data,params){
		if( params.tempNodeId ){
			var index = $servers.getCurrentCpByTempNodeId(data.rows,params.tempNodeId);
		}else{
			var index = typeof params.nodeIndex == "number" ? params.nodeIndex : $servers.getCurrentCp(data.rows);
		}
		nodesInit(data.rows,index,params);
	}

	/**
	 * 删除患者成功后的回调函数
	 */
	var ajaxUserDeleteCallBack = function(data){
		$bb.toastShow("删除成功！");
		$bb.openPage("bch_workBench");
	}

	var userDelete = function(params){
		$servers.ajaxUserDelete(params,ajaxUserDeleteCallBack);
	}

	/**
	 * 删除患者
	 */ 
	var onUserDelete = function(){
		var info = $(this).data("info");
		var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
		var channelId = $bb.getChannelId();
		var params = {
			"oprInfo":{
				"opCode":"1017",
				"opType":"2",
				"opNote":"【"+ doctorName +"】医生将【"+ info.userName +"】患者删除",
				"channelType":"2",
				"channelId":channelId,
			},
			"userInfo":{
				"userId":info.userId
			}
		};
		$bb.toastConfirmShow(userDelete,params,"确定删除该患者吗？")
	}

	/**
	 * 请求栏目模版成功后的回调函数
	 */
	var ajaxContentTemplCallBack = function(data){
		$dtext.init({
			"id":"userCustom",
			"data":data,
		});
	}

	/**
	 * 查询患者基本信息成功后的回调函数
	 */
	var ajaxUserBaseInfoCallBack = function(data,params){
		if( data.rows && data.rows.length > 0 ){
			$ui.baseInfo({
				"id":"userInfo",
				"data":data.rows[0],
			});
			$(".user-cp-name").html(data.rows[0].schemeName);
			$(function(){ $('[data-toggle="tooltip"]').tooltip() });
			$.extend(params,data.rows[0]);
			// 请求栏目模版
			//$servers.ajaxContentTempl(params,ajaxContentTemplCallBack);
			// 临床路径
			$servers.ajaxUserCpNodes(params,ajaxUserCpNodesCallBack);
			// 删除患者
			$("#userDelete").unbind("click");
			$("#userDelete").data("info",data.rows[0]);
			$("#userDelete").click(onUserDelete);
		}
	}

	/**
	 * 查询待审核任务
	 */
	/*var ajaxUserAuditTaskCallBack = function(data){
		console.log(data);
	}*/

	/**
	 * @param  {[number]} nodeIndex  [第nodeIndex个节点]
	 * @param  {[string]} tempNodeId [新增的临时节点的id]
	 */
	event.init = function(nodeIndex,tempNodeId){
		var params = $bb.getPageParams();
		if( typeof nodeIndex == "number" ) params.nodeIndex = nodeIndex;
		if( tempNodeId ) params.tempNodeId = tempNodeId; // 添加临时节点成功后的回调函数里传过来的
		// 基本信息
		$servers.ajaxUserBaseInfo(params,ajaxUserBaseInfoCallBack);
		//$servers.ajaxUserAuditTask(params,ajaxUserAuditTaskCallBack);
	}

	return event; 
});